package com.example.myapplicationndk.opengl.camerax;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.Preview;
import androidx.camera.core.SurfaceRequest;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.example.myapplicationndk.h264.H264EncodeThread;
import com.google.common.util.concurrent.ListenableFuture;

import java.util.concurrent.ExecutionException;

public class CameraView extends GLSurfaceView {


    private CameraRender cameraRender;
    private byte[] nv12;
    private H264EncodeThread h264EncodeThread;

    public CameraView(Context context) {
        super(context);
    }

    public CameraView(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }

    private void init() {
        setEGLContextClientVersion(2);
        cameraRender = new CameraRender(getContext(), mCallback);
        setRenderer(cameraRender);
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }

    public Preview.SurfaceProvider getRender() {
        if (cameraRender != null) {
            return cameraRender;
        }
        return new Preview.SurfaceProvider() {
            @Override
            public void onSurfaceRequested(@NonNull SurfaceRequest request) {
                requestRender();
            }
        };
    }

    private final CameraRender.Callback mCallback = new CameraRender.Callback() {
        @Override
        public void onSurfaceChanged() {
            setupCamera();
        }

        @Override
        public void onFrameAvailable() {
            requestRender();
        }
    };

    private void setupCamera() {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(getContext());
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                    Preview preview = new Preview.Builder().build();
                    preview.setSurfaceProvider(cameraRender);
                    cameraProvider.unbindAll();
//                    final ExecutorService executorService = Executors.newFixedThreadPool(2);
//                    ImageAnalysis imageAnalysis = new ImageAnalysis.Builder().
//                            setTargetResolution(new Size(720, 1280)) // 图片的建议尺寸
//                            .setTargetRotation(Surface.ROTATION_0) // 允许旋转后 得到图片的旋转设置
//                            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).build();
//                    imageAnalysis.setAnalyzer(executorService, new ImageAnalysis.Analyzer() {
//                        @Override
//                        public void analyze(@NonNull ImageProxy imageProxy) {
//                            int width = imageProxy.getWidth();
//                            int height = imageProxy.getHeight();
//                            ByteBuffer yBuffer = imageProxy.getPlanes()[0].getBuffer();
//                            int numPixels = (int) (width * height * 1.5f);
//                            byte[] nv21 = new byte[numPixels];
//                            byte[] nv21_rotated = new byte[numPixels];
//
//                            nv12 = new byte[numPixels];
//                            int index = 0;
//                            int yRowStride = imageProxy.getPlanes()[0].getRowStride();
//                            int yPixelStride = imageProxy.getPlanes()[0].getPixelStride();
//                            for (int y = 0; y < height; ++y) {
//                                for (int x = 0; x < width; ++x) {
//                                    nv21[index++] = yBuffer.get(y * yRowStride + x * yPixelStride);
//                                }
//                            }
//                            ImgHelper.nv21_rotate_to_90(nv21, nv21_rotated, imageProxy.getPlanes()[0].getRowStride(), preview.getResolutionInfo().getResolution().getHeight());
//
//                            ImgHelper.nv21toNV12(nv21_rotated, nv12);
//                            if (null == h264EncodeThread) {
//                                h264EncodeThread = new H264EncodeThread();
//                                h264EncodeThread.initMediaCodec(
//                                        preview.getResolutionInfo().getResolution().getWidth(),
//                                        preview.getResolutionInfo().getResolution().getHeight(),
//                                        nv12);
//                                h264EncodeThread.startEncode();
//                            }
//
//
//                        }
//                    });
                    Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner) getContext(), CameraSelector.DEFAULT_BACK_CAMERA, preview);

                } catch (ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        cameraProviderFuture.addListener(runnable, ContextCompat.getMainExecutor(getContext()));
    }
}
